package com.android.functionmanagement.receiver;

import java.text.SimpleDateFormat;
import java.util.Locale;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.android.functionmanagement.globle.ConstantGloble;
import com.android.functionmanagement.service.DaemonService;
import com.android.functionmanagement.util.DeviceUtils;
import com.android.functionmanagement.util.HeartRateUtils;
import com.android.functionmanagement.util.SharedPreferencesUtils;

public class AlarmReceiver extends BroadcastReceiver {

	private static final String TAG = "yantm";
	
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent == null || !intent.hasExtra(ConstantGloble.ALARMACTION)) {
			return;
		}
		int action = intent.getIntExtra(ConstantGloble.ALARMACTION, -1);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
		String time = format.format(System.currentTimeMillis());
		Log.e(TAG, " action = " + action + " time = " + time);

		if (action == ConstantGloble.ALARM_ACTION_GATHER_DATA) {
			boolean isGatherData = (Boolean) SharedPreferencesUtils.getParam(context, ConstantGloble.GATHER_DATA_SWITCH,
					ConstantGloble.DEFAULT_GATHER_DATA_STATUS);
			Log.e(TAG, " isGatherData = " + isGatherData);
			if (!isGatherData)
				return;
			new HeartRateUtils(context).startHeartRateDetection();
			Intent service = new Intent("android.intent.action.UPDATE_TODAY_STEP");
			context.sendBroadcast(service);
			try {
				DeviceUtils.setAlarm(context,
						ConstantGloble.ALARM_ACTION_GATHER_DATA,
						ConstantGloble.ALARM_REQUEST_GATHER_DATA,
						Integer.parseInt(SharedPreferencesUtils.getParam(
								context, ConstantGloble.GATHER_DATA_PERIOD,
								ConstantGloble.DEFAULT_GATHER_DATA_PERIOD)
								.toString()) * 60 * 1000);
			} catch (NumberFormatException e) {
				// TODO: handle exception
			}
			return;
		}
		Intent it = new Intent(context, DaemonService.class);
		it.putExtra(ConstantGloble.EXTRATYPE, intent.getIntExtra(ConstantGloble.ALARMACTION, -1));
		context.startService(it);
	}

}
